package com.coolwar.netty.intranet;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    Channel nacosChannel;
    Channel serverChannel;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object s) throws Exception {
        if (serverChannel == null) {
            serverChannel = ctx.channel();
        }
        nacosChannel = createConn();
        nacosChannel.writeAndFlush(s);
    }

    private Channel createConn() throws InterruptedException {
        if (nacosChannel != null) {
            return nacosChannel;
        }
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter());
                    }
                });
        nacosChannel = bootstrap.connect("127.0.0.1", 8848).sync().channel();
        return nacosChannel;
    }
}